<template>
  <el-main>
    <el-card>
      <!-- 添加页面标题 -->
      <div class="page-header">
        <div class="page-title">维修记录</div>
        <div class="page-subtitle">设备维修记录管理</div>
      </div>
      
      <el-tabs v-model="activeTab">
        <el-tab-pane label="全部维修记录" name="all" />
        <el-tab-pane label="办公设备维修" name="office" />
      </el-tabs>
      <el-row :gutter="10" style="margin-bottom:10px;">
        <el-col :span="6">
          <el-input v-model="searchText" placeholder="搜索设备名称/编号/报修人" clearable />
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterStatus" placeholder="全部状态" clearable style="width:100%;">
            <el-option label="全部状态" value="" />
            <el-option label="处理中" value="处理中" />
            <el-option label="已完成" value="已完成" />
          </el-select>
        </el-col>
        <el-col :span="10">
          <el-space :size="12">
            <el-button v-if="!props.isGuestMode" type="primary" @click="onShowAddDialog">报修</el-button>
            <el-button type="primary" @click="exportExcel">导出Excel</el-button>
            <el-button v-if="!props.isGuestMode" type="danger" :disabled="!multipleSelection.length" @click="onBatchDelete">批量删除</el-button>
          </el-space>
        </el-col>
      </el-row>
      <el-table
        :data="displayedRecords"
        border
        stripe
        ref="table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="repCode" label="报修单号" width="120" />
        <el-table-column prop="deviceName" label="设备名称" width="120" />
        <el-table-column prop="deviceCode" label="设备编号" width="120" />
        <el-table-column prop="reporter" label="报修人" width="100" />
        <el-table-column prop="reportTime" label="报修时间" width="140" />
        <el-table-column prop="desc" label="故障描述" width="180" />
        <el-table-column prop="status" label="处理状态" width="100" />
        <el-table-column v-if="activeTab==='office'" prop="repairPerson" label="维修人" width="120" />
        <el-table-column v-if="activeTab==='office'" prop="part" label="维修/更换部位" width="140" />
        <el-table-column v-if="activeTab==='office'" prop="outFactoryTime" label="返修（出厂）时间" width="140" />
        <el-table-column v-if="activeTab==='office'" prop="backFactoryTime" label="返回我厂时间" width="140" />
        <el-table-column v-if="activeTab==='office'" prop="effect" label="维修效果" width="180" />
        <el-table-column label="操作" width="140">
          <template #default="scope">
            <el-button
              v-if="!props.isGuestMode && scope.row.status === '处理中'"
              size="small"
              type="success"
              @click="onMarkAsDone(scope.row)"
            >完成</el-button>
            <el-button v-if="!props.isGuestMode" size="small" type="danger" @click="onDeleteRecord(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 新增报修弹窗 -->
      <el-dialog v-if="!isGuestMode" v-model="showAddDialog" title="新增报修" width="400px">
        <el-form :model="addForm">
          <el-form-item label="设备名称">
            <el-select v-model="addForm.deviceName" placeholder="请选择设备名称" filterable @change="onDeviceNameChange">
              <el-option
                v-for="item in (activeTab === 'office' ? officeDeviceNameOptions : deviceNameOptions)"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="规格型号">
            <el-select v-model="addForm.model" placeholder="请选择型号" filterable @change="onModelChange">
              <el-option v-for="item in modelOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="设备编号">
            <el-select v-model="addForm.deviceCode" placeholder="请选择设备编号" filterable allow-create>
              <el-option v-for="item in deviceCodeOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="故障描述">
            <el-input v-model="addForm.desc" type="textarea" :rows="3" placeholder="请填写故障描述" />
          </el-form-item>
          <el-form-item label="报修人">
            <el-input v-model="addForm.reporter" placeholder="请输入报修人" />
          </el-form-item>
          <template v-if="Array.isArray(allDevices.value) && allDevices.value.find(d => d.name === addForm.deviceName && d.type === '办公设备')">
            <el-form-item label="维修人">
              <el-input v-model="addForm.repairPerson" placeholder="请输入维修人/公司" />
            </el-form-item>
            <el-form-item label="维修/更换部位">
              <el-input v-model="addForm.part" placeholder="请输入维修或更换部位" />
            </el-form-item>
            <el-form-item label="返修（出厂）时间">
              <el-date-picker v-model="addForm.outFactoryTime" type="date" placeholder="请选择返修（出厂）时间" style="width:100%" />
            </el-form-item>
            <el-form-item label="返回我厂时间">
              <el-date-picker v-model="addForm.backFactoryTime" type="date" placeholder="请选择返回我厂时间" style="width:100%" />
            </el-form-item>
            <el-form-item label="维修效果">
              <el-input v-model="addForm.effect" type="textarea" placeholder="请输入维修效果" />
            </el-form-item>
          </template>
        </el-form>
        <template #footer>
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="onSubmitAddRepair">提交</el-button>
        </template>
      </el-dialog>
    </el-card>
  </el-main>
</template>

<script setup>
import { ref, computed, onMounted, inject } from 'vue'
import AV from '../leancloud'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()
const props = defineProps({
  isGuestMode: Boolean
})

const searchText = ref('');
const filterStatus = ref('');
const records = ref([]);
const multipleSelection = ref([]);
const showAddDialog = ref(false);
const addForm = ref({ deviceName: '', model: '', deviceCode: '', desc: '', reporter: localStorage.getItem('currentUsername') || '',
  repairPerson: '', part: '', outFactoryTime: '', backFactoryTime: '', effect: ''
});
const deviceNameOptions = ref([]);
const deviceCodeOptions = ref([]);
const allDevices = ref([]);
const currentUsername = localStorage.getItem('currentUsername') || ''
const modelOptions = ref([])
const activeTab = ref('all')

const filteredRecords = computed(() => {
  let result = records.value;
  if (filterStatus.value) {
    result = result.filter(r => r.status === filterStatus.value);
  }
  if (searchText.value) {
    const t = searchText.value.trim().toLowerCase();
    result = result.filter(r =>
      (r.deviceName && r.deviceName.toLowerCase().includes(t)) ||
      (r.deviceCode && r.deviceCode.toLowerCase().includes(t)) ||
      (r.reporter && r.reporter.toLowerCase().includes(t))
    );
  }
  return result;
});

const displayedRecords = computed(() => {
  if (activeTab.value === 'office') {
    // 只显示办公设备维修记录
    return filteredRecords.value.filter(r => {
      const dev = allDevices.value.find(d => d.name === r.deviceName && d.code === r.deviceCode)
      return dev && dev.type === '办公设备'
    })
  } else {
    return filteredRecords.value
  }
})

const isGuestMode = computed(() => props.isGuestMode || localStorage.getItem('isGuestMode') === 'true');

const table = ref(null);

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

async function fetchRecords() {
  const query = new AV.Query('RepairRecord');
  query.include('device');
  query.descending('createdAt');
  const results = await query.find();
  records.value = results.map(r => {
    const obj = r.toJSON();
    return {
      objectId: obj.objectId,
      repCode: obj.repCode || '',
      deviceName: obj.device?.name || '',
      deviceCode: obj.device?.code || '',
      reporter: obj.reporter || '',
      reportTime: obj.reportTime ? new Date(obj.reportTime).toLocaleString() : '',
      desc: obj.desc || '',
      status: obj.status || '',
      repairPerson: obj.repairPerson || '',
      part: obj.part || '',
      outFactoryTime: obj.outFactoryTime || '',
      backFactoryTime: obj.backFactoryTime || '',
      effect: obj.effect || ''
    }
  });
};

const exportExcel = () => {
  const data = filteredRecords.value.map(r => ({
    报修单号: r.repCode,
    设备名称: r.deviceName,
    设备编号: r.deviceCode,
    报修人: r.reporter,
    报修时间: r.reportTime,
    故障描述: r.desc,
    处理状态: r.status
  }));
  const ws = XLSX.utils.json_to_sheet(data);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '报修记录');
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
  saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '报修记录.xlsx');
};

const batchDelete = async () => {
  ElMessageBox.confirm('确定要批量删除选中的记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    for (const row of multipleSelection.value) {
      const record = AV.Object.createWithoutData('RepairRecord', row.objectId);
      await record.destroy();
    }
    ElMessage.success('删除成功');
    fetchRecords();
  });
};

async function deleteRecord(row) {
  ElMessageBox.confirm('确定要删除该记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const record = AV.Object.createWithoutData('RepairRecord', row.objectId);
    await record.destroy();
    ElMessage.success('删除成功');
    fetchRecords();
  });
};

async function markAsDone(row) {
  try {
    const record = AV.Object.createWithoutData('RepairRecord', row.objectId);
    record.set('status', '已完成');
    await record.save();
    ElMessage.success('已标记为完成');
    fetchRecords();
  } catch (e) {
    ElMessage.error('操作失败：' + (e.message || e.rawMessage));
  }
};

const onDeviceNameChange = (name) => {
  const filtered = allDevices.value.filter(d => d.name === name)
  modelOptions.value = [...new Set(filtered.map(d => d.model).filter(Boolean))]
  deviceCodeOptions.value = [...new Set(filtered.map(d => d.code).filter(Boolean))]
  if (filtered.length === 1) {
    addForm.value.model = filtered[0].model || ''
    addForm.value.deviceCode = filtered[0].code || ''
  } else {
    addForm.value.model = ''
    addForm.value.deviceCode = ''
  }
}
const onModelChange = (model) => {
  const filtered = allDevices.value.filter(d => d.name === addForm.value.deviceName && d.model === model)
  deviceCodeOptions.value = [...new Set(filtered.map(d => d.code).filter(Boolean))]
  if (filtered.length === 1) {
    addForm.value.deviceCode = filtered[0].code || ''
  } else {
    addForm.value.deviceCode = ''
  }
}

const submitAddRepair = async () => {
  // 名称+型号+编码能唯一定位设备即可，编码可为空
  const filtered = allDevices.value.filter(d =>
    d.name === addForm.value.deviceName &&
    (addForm.value.model ? d.model === addForm.value.model : true) &&
    (addForm.value.deviceCode ? d.code === addForm.value.deviceCode : true)
  )
  if (filtered.length !== 1) {
    ElMessage.error('请选择能唯一定位的设备（名称+型号+编码）')
    return
  }
  const device = filtered[0]
  // 生成报修单号
  function generateRepCode() {
    // 生成一个大写字母+六位数字的报修单号，如 R123456
    const letter = String.fromCharCode(65 + Math.floor(Math.random() * 26));
    const number = Math.floor(100000 + Math.random() * 900000); // 保证六位
    return `${letter}${number}`;
  }
  const repCode = generateRepCode();
  const RepairRecord = AV.Object.extend('RepairRecord');
  const record = new RepairRecord();
  record.set('device', AV.Object.createWithoutData('Device', device.objectId));
  record.set('repCode', repCode);
  record.set('desc', addForm.value.desc);
  record.set('reporter', currentUsername);
  record.set('reportTime', new Date());
  record.set('status', '处理中');
  // 如果是办公设备，保存专属字段
  if (device.type === '办公设备') {
    record.set('repairPerson', addForm.value.repairPerson || '')
    record.set('part', addForm.value.part || '')
    record.set('outFactoryTime', addForm.value.outFactoryTime || '')
    record.set('backFactoryTime', addForm.value.backFactoryTime || '')
    record.set('effect', addForm.value.effect || '')
  }
  console.log('报修 deviceId:', device.objectId, 'repCode:', repCode);
  try {
    await record.save();
    ElMessage.success('报修已提交');
  } catch (e) {
    ElMessage.error('报修保存失败: ' + (e.message || e.rawMessage));
    console.error('报修保存失败', e);
  }
  fetchRecords();
};

const getDeviceNameOptions = () => {
  return [...new Set(allDevices.value.map(d => d.name).filter(Boolean))];
};

const getDeviceCodeOptions = (name) => {
  const filtered = allDevices.value.filter(d => d.name === name);
  return filtered.map(d => d.code);
};

const officeDeviceNameOptions = computed(() => {
  return [...new Set(allDevices.value.filter(d => d.type === '办公设备').map(d => d.name).filter(Boolean))];
});

const showLogin = inject('showLogin')

function requireLogin(action) {
  if (isGuestMode.value) {
    ElMessage.warning('请先登录后操作')
    localStorage.setItem('loginRedirect', router.currentRoute.value.fullPath)
    showLogin && showLogin()
    return
  }
  action()
}
// 包装操作
function onShowAddDialog() {
  if (isGuestMode.value) {
    ElMessage.warning('请先登录后操作');
    showLogin && showLogin();
    return;
  }
  // 重置表单内容，防止tab切换后内容不刷新
  addForm.value = { deviceName: '', model: '', deviceCode: '', desc: '', reporter: localStorage.getItem('currentUsername') || '',
    repairPerson: '', part: '', outFactoryTime: '', backFactoryTime: '', effect: ''
  };
  showAddDialog.value = true;
}
function onSubmitAddRepair() {
  if (isGuestMode.value) {
    ElMessage.warning('请先登录后操作');
    showLogin && showLogin();
    return;
  }
  submitAddRepair();
}
function onBatchDelete() { requireLogin(batchDelete) }
function onDeleteRecord(row) { requireLogin(() => deleteRecord(row)) }
function onMarkAsDone(row) { requireLogin(() => markAsDone(row)) }

onMounted(async () => {
  fetchRecords();
  // 获取所有设备信息
  const query = new AV.Query('Device');
  query.limit(1000);
  const results = await query.find();
  allDevices.value = results.map(d => d.toJSON());
  deviceNameOptions.value = getDeviceNameOptions();
});
</script>

<style scoped>
/* 统一按钮样式 */
.repair-actions .el-button {
  font-weight: 600;
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 6px;
  gap: 6px;
  height: 36px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.repair-actions .el-button[type="primary"] {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: 1px solid #409eff;
  color: white;
}

.repair-actions .el-button[type="primary"]:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d5aa0 100%);
  border-color: #337ecc;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

.repair-actions .el-button[type="danger"] {
  background: linear-gradient(135deg, #f56c6c 0%, #e74c3c 100%);
  border: 1px solid #f56c6c;
  color: white;
}

.repair-actions .el-button[type="danger"]:hover {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
  border-color: #e74c3c;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(245, 108, 108, 0.3);
}

/* 表格中的按钮样式 */
.el-table .el-button {
  font-weight: 600;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  gap: 4px;
  height: 28px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.el-table .el-button[type="danger"] {
  background: linear-gradient(135deg, #f56c6c 0%, #e74c3c 100%);
  border: 1px solid #f56c6c;
  color: white;
}

.el-table .el-button[type="danger"]:hover {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
  border-color: #e74c3c;
  transform: translateY(-1px);
  box-shadow: 0 3px 6px rgba(245, 108, 108, 0.3);
}

/* 对话框中的按钮样式 */
.el-dialog .el-button {
  font-weight: 600;
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 6px;
  gap: 6px;
  height: 36px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.el-dialog .el-button[type="primary"] {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: 1px solid #409eff;
  color: white;
}

.el-dialog .el-button[type="primary"]:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d5aa0 100%);
  border-color: #337ecc;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

/* 确保按钮内容居中 */
.el-button .el-button__content {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 20px;
  text-align: center;
}

/* 页面标题样式已移至全局样式文件 */

@media (max-width: 700px) {
  .el-main {
    padding: 4px !important;
  }
  .page-header {
    text-align: left;
    padding-left: 10px;
    padding-bottom: 5px;
  }
  /* 页面标题样式已移至全局样式文件 */
  .el-row {
    flex-direction: column !important;
    gap: 0;
  }
  .el-col {
    width: 100% !important;
    max-width: 100% !important;
    flex: 1 1 100%;
  }
  .el-table {
    font-size: 13px;
    min-width: 600px;
    overflow-x: auto;
    display: block;
  }
  .el-table__body-wrapper {
    overflow-x: auto !important;
  }
  .el-button, .el-input, .el-select {
    font-size: 16px !important;
    min-height: 38px !important;
  }
  .el-pagination {
    font-size: 15px;
    padding: 8px 0;
  }
  .el-dialog {
    width: 98vw !important;
    min-width: unset !important;
    max-width: 100vw !important;
    margin: 0 auto;
  }
  .el-form-item__label {
    font-size: 15px !important;
  }
}
</style>
